<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\Banner;
use App\Models\Family;
use App\Models\ClaimProject;
use App\Models\ClaimProjectCategory;
use App\Models\ClaimProjectServiceObj;
use App\Models\News;
use App\Models\Org;
use App\Models\Platform;
use App\Models\Project;
use App\Models\SmsCode;
use App\Models\Team;
use App\Models\User;
use App\Models\UserClaimProject;
use App\Models\UserCollection;
use App\Models\UserProject;
use App\Models\UserTeam;
use App\Models\Volunteer;
use App\Models\VolunteerGoodAt;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;

class PlatformController extends Controller
{

    public function index()
    {
        $platInfo = Platform::gePlatformInfo();

        if(empty($platInfo) || empty($platInfo->org_list))
        {
            $this->setStatus(10001);
            $this->setMsg('平台配置错误，没有设置相关机构');
            return $this->response();
        }

        $banner = Banner::platformBanner($platInfo->id);
        $blackTeam = Team::whereIn('org_id', $platInfo->org_list)->where('in_blacklist', 1)->pluck('id')->toArray();

        $nodes = Project::with('team')->whereIn('org_id', $platInfo->org_list)->where('status', 1)->where('verify_status', 1)->whereRaw('recommend_time is not null')->whereNotIn('team_id', $blackTeam);
        $nodes = $nodes->orderBy('publish_time', 'desc');
        $nodes = $nodes->orderBy('id', 'desc');
        $nodes = $nodes->skip(0)->take(10);
        $nodes = $nodes->get();

        foreach($nodes as $node)
        {
            $tmp = Project::format($node);
            $tmp['project_status'] = Project::projectStatus($node);
            $tmp['distance'] = $node->getDistance();
            $tmp['team'] = Team::format($node->team);
            $tmp['org_info'] = $node->org->getAllInfo();
            $project[] = $tmp;
        }

        //news

        $nodes = News::where('status', 1)->orderby('is_recommend', 'desc')->where('platform_id', $platInfo->id)->orderBy('publish_time', 'desc')->take(2)->get();
        $news = [];
        foreach($nodes as $value)
        {
            $news[] = News::format($value);
        }

        $data['banner'] = $banner;
        $data['project'] = $project;
        $data['news'] = $news;

        $this->setData($data);
        return $this->response();

    }


    public function project(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $platInfo = Platform::gePlatformInfo();

        if(empty($platInfo) || empty($platInfo->org_list))
        {
            $this->setStatus(10001);
            $this->setMsg('平台配置错误，没有设置相关机构');
            return $this->response();
        }

        $name = $request->input('name');


        $blackTeam = Team::whereIn('org_id', $platInfo->org_list)->where('in_blacklist', 1)->pluck('id')->toArray();
        $nodes = Project::with(['team','category', 'serviceObj'])->whereIn('org_id', $platInfo->org_list)->where('status', 1)->where('verify_status', 1)->whereNotIn('team_id', $blackTeam);
        if(!empty($name))//名称检索
        {
            $nodes = $nodes->where('name', 'like', "%{$name}%");
        }

        $count = $nodes->count();

        $nodes = $nodes->orderBy('pri', 'asc');

        $nodes = $nodes->orderBy('id','desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();
        $list = [];
        foreach($lists as $value)
        {
            $tmp = $value->getAllInfo();
            $tmp['org_info'] = $value->org->getAllInfo();
            $list[] = $tmp;
        }

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }

    public function org(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $platInfo = Platform::gePlatformInfo();

        if(empty($platInfo) || empty($platInfo->org_list))
        {
            $this->setStatus(10001);
            $this->setMsg('平台配置错误，没有设置相关机构');
            return $this->response();
        }

        $name = $request->input('name');


        $nodes = Org::whereIn('id', $platInfo->org_list);

        $count = $nodes->count();

        if(!empty($name))//名称检索
        {
            $nodes = $nodes->where('name', 'like', "%{$name}%");
        }

        $nodes = $nodes->orderBy('id','desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();
        $list = [];
        foreach($lists as $value)
        {
            $tmp = $value->getAllInfo();
            $tmp['project_count'] = $value->projectCount();
            $tmp['reward_time'] = $value->rewardTime();

            $list[] = $tmp;
        }

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }

    public function volunteerInfo(Request $request)
    {
        $idno = $request->get('id_number');

        $platInfo = Platform::gePlatformInfo();

        if(empty($platInfo) || empty($platInfo->org_list))
        {
            $this->setStatus(10001);
            $this->setMsg('平台配置错误，没有设置相关机构');
            return $this->response();
        }

        $volunteer = Volunteer::whereIn('org_id', $platInfo->org_list)->where('id_number', $idno)->first();

        if(empty($volunteer))
        {
            return $this->response();
        }

        $data['volunteer_info'] = $volunteer->user->getAllInfo();

        $nodes =  Volunteer::whereIn('org_id', $platInfo->org_list)->where('id_number', $idno)->get();

        $data['org_count'] = count($nodes);
        foreach ($nodes as $node)
        {
            $userIds[] = $node->user_id;
        }

        $data['team_count'] = UserTeam::whereIn('user_id', $userIds)->where('verify_status', 1)->count();
        $data['project_count'] = UserProject::whereIn('user_id', $userIds)->where('verify_status', 1)->count();
        $data['team_count'] = UserTeam::whereIn('user_id', $userIds)->where('verify_status', 1)->count();
        $data['reward_time'] = Volunteer::whereIn('user_id', $userIds)->sum('reward_time');


        $nodes = UserProject::whereIn('user_id', $userIds)->where('verify_status', 1)->orderby('id', 'desc')->get();

        $projectList = [];
        foreach($nodes as $node)
        {
            $tmp = [];

            $tmp['org'] = $node->project->org->getAllInfo();
            $tmp['project'] = $node->project->getAllInfo();
            $tmp['reward_time'] = $node->reward_time;

            $projectList[] = $tmp;
        }

        $data['project_list'] = $projectList;


        $this->setData($data);
        return $this->response();
    }

    public function team(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $platInfo = Platform::gePlatformInfo();

        if(empty($platInfo) || empty($platInfo->org_list))
        {
            $this->setStatus(10001);
            $this->setMsg('平台配置错误，没有设置相关机构');
            return $this->response();
        }

        $name = $request->input('name');
        $nodes = Team::query();
        $nodes = $nodes->where('verify_status', 1)->where('in_blacklist', 0)->whereIn('org_id', $platInfo->org_list);
        if(($cityCode = $this->getCityCode()))
        {
            $nodes = $nodes->where('city_id', $cityCode);
        }

        if($request->has('service_object') && !empty($serviceObject= $request->input('service_object')))
        {
            $serviceObject = is_array($serviceObject)? $serviceObject:explode(',', $serviceObject);
            $objCount = count($serviceObject);
            $tids = TeamServiceObj::where('org_id', $this->getOrdId())->whereIn('service_object_name', $serviceObject)->groupBy('team_id')->havingRaw("count(*) ={$objCount}")->get(['team_id'])->toArray();

            $ids = array_map(function($node){
                return $node['team_id'];
            }, $tids);

            $nodes->whereIn('id', $ids);
        }

        if($request->has('service_category') && !empty($serviceCategory= $request->input('service_category')))
        {
            $serviceCategory = is_array($serviceCategory)? $serviceCategory:explode(',', $serviceCategory);
            $cateCount = count($serviceCategory);
            $tids = TeamCategory::where('org_id', $this->getOrdId())->whereIn('service_category_name', $serviceCategory)->groupBy('team_id')->havingRaw("count(*) ={$cateCount}")->get(['team_id'])->toArray();

            $ids = array_map(function($node){
                return $node['team_id'];
            }, $tids);
            $nodes->whereIn('id', $ids);
        }

        if($request->has('team_type'))
        {
            $nodes = $nodes->where('type', $request->input('team_type'));
        }

        if($request->has('county_id'))
        {
            $nodes = $nodes->where('county_id', $request->input('county_id'));
        }

        if(!empty($name))
        {
            $nodes->where('name', 'like', "%{$name}%");
        }
        $count = $nodes->count();
        $nodes = $nodes->orderBy('id','desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize)
        ];

        $list = [];
        foreach($lists as $value)
        {
            $tmp = Team::format($value);
            $tmp['org_info'] = $value->org->getAllInfo();
            $list[] = $tmp;
        }

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }

    public function claim(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $platInfo = Platform::gePlatformInfo();

        if(empty($platInfo) || empty($platInfo->org_list))
        {
            $this->setStatus(10001);
            $this->setMsg('平台配置错误，没有设置相关机构');
            return $this->response();
        }

        $nodes = ClaimProject::whereIn('org_id', $platInfo->org_list)->where('status', 1);
        $name = $request->get('name');
        if(!empty($name))//名称检索
        {
            $nodes = $nodes->where('name', 'like', "%{$name}%");
        }

        $count = $nodes->count();

        $nodes = $nodes->orderBy('publish_time','desc');

        $lists = $nodes->take($pageSize)->skip($from)->get();
        $list = [];
        foreach($lists as $value)
        {
            $tmp = $value->getAllInfo();
            $tmp['org_info'] = $value->org->getAllInfo();
            $list[] = $tmp;
        }

        $pageInfo = [
                "current_page" => intval($pageNum),
                "total_page" => ceil($count / $pageSize),
                "page_size" => intval($pageSize),
                "count" => $count,

        ];

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }


    public function news(Request $request)
    {
        $pageNum = request()->input('current_page', 1);
        $pageSize = request()->input('page_size', 10);
        $from = ($pageNum - 1)*$pageSize;

        $platInfo = Platform::gePlatformInfo();

        $nodes = News::where('status', 1)->where('platform_id', $platInfo->id);


        $count = $nodes->count();
        $nodes = $nodes->orderby('is_recommend', 'desc')->orderBy('publish_time', 'desc');
        $nodes = $nodes->take($pageSize)->skip($from)->get();

        $list = [];
        foreach($nodes as $value)
        {
            $list[] = News::format($value);

        }

        $pageInfo = [
            "current_page" => intval($pageNum),
            "total_page" => ceil($count / $pageSize),
            "page_size" => intval($pageSize),
            "count" => $count,
        ];

        $data['list'] = $list;
        $data['page'] = $pageInfo;
        $this->setData($data);

        return $this->response();
    }
}
